import { Coupon, CouponService } from "@mallfoundry/marketing/coupon"
import { Card } from "antd"
import * as _ from "lodash"
import * as React from "react"
import { useState } from "react"
import { useHistory, useLocation, useParams } from "react-router-dom"
import Page from "../../components/page"
import { messageError } from "../../utils/reason"
import CouponForm from "./coupon-form"
import classes from "./coupon-new.module.scss"

export default function CouponNew() {
  const { storeId = "" } = useParams<{ storeId: string }>()
  const location = useLocation()
  const history = useHistory()
  const search = new URLSearchParams(location.search)
  const type = search.get("type")
  const [coupon] = useState(_.assign(new Coupon(), { storeId, type }))
  const [loading, setLoading] = useState(false)

  function onSave(aCoupon: Coupon) {
    setLoading(true)
    CouponService
      .addCoupon(aCoupon)
      .then(() => setLoading(false))
      .then(() => history.push(`/stores/${storeId}/coupons`))
      .catch((reason: string) => {
        messageError(reason)
        setLoading(false)
      })
  }

  return (<div className={classes.CouponNew}>
    <Page.Header title="添加优惠券" ghost={false}/>
    <Page.Content>
      <Card>
        <CouponForm loading={loading}
                    coupon={coupon}
                    onFinish={onSave}
                    onCancel={() => history.push(`/stores/${storeId}/coupons`)}/>
      </Card>
    </Page.Content>
  </div>)
}
